package com.example.h9iserver.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.h9iserver.domain.CustomUserDetails;
import com.example.h9iserver.domain.User;
import com.example.h9iserver.domain.dto.UserDto;
import com.example.h9iserver.domain.query.LoginQuery;
import com.example.h9iserver.service.UserService;
import com.example.h9iserver.mapper.UserMapper;
import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Service;

/**
 * @author 4040
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-07-29 09:40:05
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    private final UserDetailsService userDetailsService;

    private final AuthenticationManager authenticationManager;

    @Override
    public UserDto login(LoginQuery loginQuery) {
        // 构建认证令牌
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginQuery.getUsername(), loginQuery.getPassword())
        );
        // 将认证信息存入 SecurityContext
        SecurityContextHolder.getContext().setAuthentication(authentication);

        return getCurrentUser();
    }

    @Override
    public UserDto getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(userDetails, userDto);
        return userDto;
    }
}




